#!/usr/bin/env python
import os
import time


# 文件路径
PATH = os.path.dirname(os.path.abspath(__file__))

# 配色方案
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
RED = "\033[31m"
NORMAL = "\033[0m"
PURPLE = "\033[35m"

# Git status
STATUS_DICT = {
    "unstaged": "Changes not staged for commit:",
    "uncommitted": "Changes to be committed:",
    "committed": "nothing to commit",
    "untracked": "nothing added to commit but untracked files present",
    "lost": "repo lost",
}

# status to color
COLOR_DICT = {
    "unstaged": RED,
    "uncommitted": YELLOW,
    "committed": GREEN,
    "untracked": BLUE,
    "lost": NORMAL,
}


def monitor():
    while 1:
        # 读取repos list
        with open(PATH + "/repos.txt", "r+", encoding="utf-8") as f:
            repos = f.readlines()
        # 标题
        items = "\n" + "\t" + CYAN + "All repos status:\n" + NORMAL
        # 遍历repo
        for n, r in enumerate(repos):
            # 初始化cmd及path
            cmd = False
            # 去掉 \n 避免bug
            r = r.strip("\n")

            # command格式特殊处理
            if "||" in r:
                r, cmd = r.split("||")

            # 判断目录是否存在
            if not os.path.exists(r):
                # 目录不存在时打印信息
                item = (
                    "\t"
                    + str(n)
                    + "\t"
                    + COLOR_DICT["lost"]
                    + STATUS_DICT["lost"]
                    + NORMAL
                    + "\t"
                    + r
                    + "\n"
                )
                items += item
                continue

            # 获取命令返回值
            cmd = cmd if cmd else f"cd {r} && git status"
            ret = os.popen(cmd).read()

            # 构建打印信息
            for k, v in STATUS_DICT.items():
                if v in ret:
                    item = (
                        "\t"
                        + str(n)
                        + "\t"
                        + COLOR_DICT[k]
                        + k
                        + NORMAL
                        + "\t"
                        + r
                        + "\n"
                    )
                    items += item
                    break

        print(items)

        # 管理功能交互信息
        man_str = f"""
        \t{CYAN}Select your operation:{NORMAL}
        \t{PURPLE}Add repo:{NORMAL}\tadd PATH
        \t{PURPLE}Del repo:{NORMAL}\tdel NUMBER
        \t{PURPLE}Command:{NORMAL}\tcmd PATH||COMMAND
        \t{PURPLE}Scan dir:{NORMAL}\tscan PATH
        \t>>>
        """
        # 交互控制
        try:
            select = input(man_str)
        except KeyboardInterrupt:
            exit()
        # 执行管理操作
        with open(PATH + "/repos.txt", "w", encoding="utf-8") as f:
            try:
                # 指令判断
                if select.startswith("add "):
                    repos.append(select[4:] + "\n")
                elif select.startswith("del "):
                    del repos[int(select[3:])]
                elif select.startswith("cmd "):
                    repos.append(select[4:] + "\n")
                elif select.startswith("scan "):
                    repos = find_repo(repos, select[5:])
                else:
                    f.writelines(repos)
                    exit()
            except Exception as e:
                print(e)
                time.sleep(2)
            f.writelines(repos)
            # 循环清屏
            os.system("cls")


def find_repo(repos, spath):
    # 执行find command
    cmd = f"find {spath} -name '.git'"
    ret = os.popen(cmd).readlines()
    # 遍历查重
    for r in ret:
        # 获取.git所在目录
        r = os.path.dirname(r) + "\n"
        if r in repos:
            continue
        repos.append(r)

    return repos
